
import { _decorator, Component, Node, Label, ProgressBar, VERSION, sys } from 'cc';
import { App } from '../App';
import { ButtonFlag, EventConst, HotUpdateState, ModuleConst } from '../core/Common';
const { ccclass, property } = _decorator;

/**
 * Predefined variables
 * Name = HotUpdate
 * DateTime = Thu Dec 30 2021 21:13:18 GMT+0800 (中国标准时间)
 * Author = yang839
 * FileBasename = HotUpdate.ts
 * FileBasenameNoExtension = HotUpdate
 * URL = db://assets/src/HotUpdate.ts
 * ManualUrl = https://docs.cocos.com/creator/3.4/manual/zh/
 *
 */
 
@ccclass('HotUpdate')
export class HotUpdate extends Component {
    @property({type:Node})
    updateNode:Node = null;
    @property({type:Node})
    loginNode:Node;
    @property({type:Label})
    lblVersion:Label = null;
    @property({type:Label})
    lblEngine:Label = null;
    @property({type:ProgressBar})
    progress:ProgressBar = null;

    start () {
        this.lblVersion.string = App.getValue('version');
        this.lblEngine.string = `cocos creator:${VERSION}`;
        this.updateNode.active = true;
        this.loginNode.active = false;

        this.progress.progress = 0;

        App.Event.on(EventConst.HOT_UPDATE_MODULE,this._updateCall,this);
        App.Native.update(ModuleConst.MASTER);
    }

    onEntryClicket(){
        App.runScene('hall');
    }

    onSdkClicket(_,flag:string){
        if (!sys.isNative){
            return ;
        }
    }

    onServerClicket(_,flag:string){
        App.openView('HtmlView',flag);
    }

    private _updateCall(module:string,state:HotUpdateState,...args:any) {
        switch(state){
            case HotUpdateState.Finish:
                App.popTip('');
            case HotUpdateState.Skip:{
                this.loginNode.active = true;
                this.updateNode.active = false;
                break ;
            }

            case HotUpdateState.New:{
                App.showMessageBox('',(flag:ButtonFlag)=>{
                    flag === ButtonFlag.Ok && App.Event.emit(EventConst.HOT_UPDATE_MODULE,HotUpdateState.Update);
                });
                break ;
            }

            case HotUpdateState.Progress:{
                this.progress.progress = args[0]/args[1];
                break ;
            }

            case HotUpdateState.Error:{
                App.showMessageBox(args[0]);
                break ;
            }
        }
    }
}
